package com.example.struts;

import com.example.Utils.CommonStringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HttpParams {
    private HttpServletRequest request;

    public HttpParams(HttpServletRequest request) {
        this.request = request;
    }

    public String getParam(String key) {
        String param = request.getParameter(key);
        return param;
    }

    public String getParam(String key, String defaultValue) {
        String param = request.getParameter(key);
        if (param == null) {
            return defaultValue;
        }
        return param;
    }

    public Integer getIntParam(String key) {
        String param = request.getParameter(key);
        if (param == null) {
            return null;
        }
        Integer IntValue = CommonStringUtils.safeInteger(param);
        return IntValue;
    }

    public Integer getIntParam(String key, Integer defaultValue) {
        String param = request.getParameter(key);
        if (param == null) {
            return defaultValue;
        }
        Integer IntValue = CommonStringUtils.safeInteger(param);
        return IntValue;
    }

    public Double getDoubleParam(String key) {
        String param = request.getParameter(key);
        if (param == null) {
            return null;
        }
        Double doubleValue = CommonStringUtils.safeDouble(param);
        return doubleValue;
    }

    public Double getDoubleParam(String key, Double defaultValue) {
        String param = request.getParameter(key);
        if (param == null) {
            return defaultValue;
        }
        Double doubleValue = CommonStringUtils.safeDouble(param);
        return doubleValue;
    }

    public Boolean getBooleanParam(String key) {
        String param = request.getParameter(key);
        if (CommonStringUtils.isNullOrEmpty(param)) {
            return null;
        }
        Boolean booleanValue;
        try {
            booleanValue = Boolean.valueOf(param);
        } catch (Exception e) {
            return null;
        }
        return booleanValue;
    }

    public Boolean getBooleanParam(String key, Boolean defaultValue) {
        String param = request.getParameter(key);
        if (CommonStringUtils.isNullOrEmpty(param)) {
            return defaultValue;
        }
        Boolean booleanValue;
        try {
            booleanValue = Boolean.valueOf(param);
        } catch (Exception e) {
            return defaultValue;
        }
        return booleanValue;
    }

    public void printParameter() {
        Map<String, String[]> map = request.getParameterMap();
        Set<String> keys = map.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            System.out.println(String.format("{%s : %s}", key, Arrays.toString(map.get(key))));
        }
    }
}
